/*
   loadappliance.js: the workhorse of the loader
   $Id$

   Copyright 2010-2011 Portland Transport

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

   Authors:
   Matt Conway: main code

*/


function trArrServiceBARTCreateUpdaters(arrivals_object, service_requests, updaters) {
    sRqs = service_requests;
    for (var request in service_requests.BART) {
	updaters.push(new trArrBARTUpdater(service_requests.BART[request], arrivals_object));
    }
}

function trArrBARTUpdater (request, arrivals_object) {
    console.log('Building BART updater');
    this.arrivals_queue = [];

    globRq = request;

    console.log('1');
    
    // So it is in the closure
    var updater = this;

    console.log('2');

    var stop_id_list = [request.stop_id];

    console.log(request.stop_data.avl_stop_id);

    this.url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D%22http%3A%2F%2Fapi.bart.gov%2Fapi%2Fetd.aspx%3Fcmd%3Detd%26orig%3D' + request.stop_data.avl_stop_id + '%26key%3DMW9S-E7SL-26DU-VV8V%22&diagnostics=true';

    console.log('setting up arrs queue');
    
    this.arrivals = function () {
	return this.arrivals_queue;
    }

    console.log('Setting up BART request loop');

    this.requestLoop = function () {
	console.log('Making BART request to ' + this.url);
	jQuery.ajax({
	    url: this.url,
	    cache: false,
	    dataType: 'xml',
	    success: function(data) {
		// There's a possibility this won't work in IE
		var xml = jQuery(data);
		globXML = xml;

		console.log('Made BART Request');
		var local_queue = [];
		// Assemble their strings into a date-time pair, then parse
		var update_time = Date.parse(xml.find('date').text() + ' ' + xml.find('time').text());

		// Loop through each estimate and build an entry
		xml.find('estimate').each( function (ind, estDoc) {
		    var est = jQuery(estDoc); // Again, maybe not in IE
		    var entry = {};
		    var date = new Date(update_time);
		    var mins = est.find('minutes').text();
		    if (mins == 'Arrived') mins = 0; // Handle the 'Arrived' case.
		    mins = Number(mins);
		    date.setMinutes(date.getMinutes() + mins)
		    entry.arrivalTime = date.getTime();
		    entry.type = 'estimated';
		    entry.headsign = est.parent().find('destination').text();
		    entry.stop_data = copyStopData(request.stop_data);
		    entry.stop_id = est.parent().find('abbreviation').text();
		    entry.route_id = ''; // Can't get from RealBART
		    entry.route_data = {};
		    entry.alerts = xml.find('message').text();
		    entry.agency = 'BART';
		    entry.avl_agency = 'BART';
		    entry.last_updated = update_time;
		    console.log(entry);
		    local_queue.push(entry);
		});
		updater.arrivals_queue = local_queue;
	    }
	});
    }

    console.log('Preparing first BART request');
    this.requestLoop();
    setInterval(this.requestLoop, 60*1000); // Minutely
}
					 


function copyStopData(data) {
  var out = {};
  for (var element in data) {
    // strip it down to just the GTFS elements
    if (element != 'routes' && element != 'geometry' && element != 'doc_type' && element.substring(0,1) != '_') {
      out[element] = data[element]
    }
  }
  return out;
}